package com.xiaomaoguai.fcp.pre.kepler.trace.configuration;

import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.util.ThreadLocalScopeManager;
import org.slf4j.MDC;

/**
 * @author August.Zhang
 * @version v1.0.0
 * @date 2020/1/17 14:47
 * @since JDK 1.8
 */
public class WrappedThreadLocalScopeManager extends ThreadLocalScopeManager {

	public void putB3TraceInfo(Span span) {
		if (span != null && span.context() != null) {
			String[] traceInfo = span.context().toString().split(":");
			if (traceInfo.length == 4) {
				MDC.put("X-B3-TraceId", traceInfo[0]);
				MDC.put("X-B3-SpanId", traceInfo[1]);
				MDC.put("X-B3-ParentSpanId", traceInfo[2]);
			}
		}
	}

	@Override
	public Scope activate(Span span, boolean finishOnClose) {
		putB3TraceInfo(span);
		return super.activate(span, finishOnClose);
	}

	@Override
	public Scope activate(Span span) {
		putB3TraceInfo(span);
		return super.activate(span);
	}

}
